﻿using System;
using System.Collections.Generic;
using System.Data;

namespace HYFamilyLibDataManager
{
	public class SqlServerSubjectTable : ISubjectTable
	{
		public SqlServerSubjectTable(SqlServerDatabase db)
		{
			this.mDatabase = db;
		}

		public DbSubject this[Guid id]
		{
			get
			{
				DataTable dataTable = this.mDatabase.ExecQuery(string.Format("select [SubjectName],[Version] from [SubjectTable] where [GUID]='{0}'", id.ToString()));
				if (dataTable != null)
				{
					DbSubject dbSubject = new DbSubject(dataTable.Rows[0][0].ToString().Trim(), id);
					dbSubject.Version = dataTable.Rows[0][1].ToString();
					dbSubject.SetDatabase(this.mDatabase);
					return dbSubject;
				}
				return null;
			}
		}

		public List<DbSubject> AllSubject()
		{
			List<DbSubject> list = new List<DbSubject>();
			DataTable dataTable = this.mDatabase.ExecQuery(string.Format("select [SubjectName],[Version],[GUID] from [SubjectTable]", Array.Empty<object>()));
			if (dataTable != null)
			{
				for (int i = 0; i < dataTable.Rows.Count; i++)
				{
					DbSubject dbSubject = new DbSubject(dataTable.Rows[i][0].ToString().Trim(), new Guid(dataTable.Rows[i][2].ToString()));
					dbSubject.Version = dataTable.Rows[i][1].ToString();
					dbSubject.SetDatabase(this.mDatabase);
					list.Add(dbSubject);
				}
			}
			return list;
		}

		public SubjectType SubjectType
		{
			get
			{
				string a = this.AllSubject()[0].Guid.ToString().Trim();
				if (a == "d27c7e1b-40cd-4b2f-83e2-c5c14b98a80a")
				{
					return SubjectType.Architecture;
				}
				if (a == "be10f82f-915a-4e0f-99d0-8f35b568e7aa")
				{
					return SubjectType.Electric;
				}
				if (a == "28bd20ce-8cc7-474c-a21b-db084ad93f77")
				{
					return SubjectType.HVAC;
				}
				if (a == "cc9eeaee-4273-4406-a35b-7903804829ad")
				{
					return SubjectType.Plumbing;
				}
				if (a == "1c7d0e47-274a-4aee-9827-866f6c62719a")
				{
					return SubjectType.System;
				}
				if (!(a == "3c5d6e47-274a-4aee-9827-866f6c62719a"))
				{
					return SubjectType.Architecture;
				}
				return SubjectType.Project;
			}
		}

		public string GetVersion()
		{
			string result = "0";
			string sqlStr = string.Format("select Version from SubjectTable", Array.Empty<object>());
			DataTable dataTable = this.mDatabase.ExecQuery(sqlStr);
			if (dataTable != null && dataTable.Rows.Count > 0)
			{
				result = dataTable.Rows[0]["Version"].ToString();
			}
			return result;
		}

		public void SetVersion(string ver)
		{
			string sqlStr = string.Format("UPDATE SubjectTable SET Version = '{0}'", ver);
			this.mDatabase.ExecQuery(sqlStr);
		}

		private SqlServerDatabase mDatabase;
	}
}
